// import NProgress from '@/plugins/nprogress';
import * as NProgress from 'nprogress';
import { components, useUserStore } from "@/store";
import { RouteRecordRaw, Router } from "vue-router";
import dynamicRoutes from "./dynamicRoutes";
import staticRoutes from "./staticRoutes";

const permission = (router: Router) => {
    // visitor角色白名单
    const UN_LOGIN_WHITE_LIST = ['/login', '/register', '/errorPage', '/article', '/log', '/about', '/test'];
    // user角色白名单
    const USER_WHITE_LIST = [...UN_LOGIN_WHITE_LIST, '/write'];

    router.beforeEach(async (to, from, next) => {
        NProgress.start();

        const userStore = useUserStore();
        // 是否已注册动态路由
        const IS_REGISTER_ROUTES = router.getRoutes().length > staticRoutes.length;

        // 未登录
        if (!userStore.token) {
            if (userStore.role === 'user' && USER_WHITE_LIST.includes(to.path) && IS_REGISTER_ROUTES) {
                next();
                return;
            }
        } else {
            // 已登录

        }

        if (!IS_REGISTER_ROUTES) {
            const routes = await filterRoutesByRole(dynamicRoutes, userStore.role);
            const homePage = staticRoutes.find(route => route.path === '/home');
            routes.unshift(homePage);

            routes.forEach(route => router.addRoute(route));
            console.log('动态路由已注册');

            components.useHeaderStore()._setHeaderRoutes(routes);
            console.log('导航栏路由生成');

            next({ ...to, replace: true });
            return;
        }

        next();
    })


    router.afterEach((to, from) => {
        NProgress.done();
    })
}

async function filterRoutesByRole(routes: RouteRecordRaw[], role: string): Promise<RouteRecordRaw[]> {
    const r = [];
    for (let i = 0; i < routes.length; i++) {
        const route = routes[i];
        if (route.meta.roles && route.meta?.roles?.includes(role)) {
            if (route.children) {
                route.children = await filterRoutesByRole(route.children, role);
            }
            r.push(route);
        }
    }
    return r;
}

export default permission;
